package com.hsyt.pms.support.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SpringConfigLoader implements ApplicationContextAware {

    private static Properties props;

    private static ApplicationContext applicationContext;

    public static synchronized ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static synchronized void init(ApplicationContext applicationContext1) {
        if (applicationContext == null)
            applicationContext = applicationContext1;
    }

    public static synchronized void loadProperty(String pathFile) {
        InputStream fis = null;
        try {
            if (props == null) {
                props = new Properties();
                fis = new FileInputStream(new File(pathFile));
                props.load(fis);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }

    public static String getProperty(String key) {
        return props.getProperty(key);
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> beanType) {
        return (T) applicationContext.getBean(name, beanType);
    }

    public static <T> T getBean(Class<T> beanType) {
        return applicationContext.getBean(beanType);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        init(applicationContext);
    }
}
